// pages/room/playing/playing.js
var app = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    voice: {
      type: Boolean,
      value: false,
    },
    rtmpUrl: {
      type: String,
      value: null,
    },
    gameInfo: {
      type: Object,
      value: null,
      observer: function (newVal, oldVal) {
        if (newVal) {
          this.gameStart();
        }
      }
    },
    roomStatus: {
      type: String,
      value: '',
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    pageHeight: app.globalData.pageHeight,
    videoAreaHeight: 909,
    showResult: false,
    gameResult: 1,
    time: 20,
    dirKey: {
      left: 'left',
      right: 'right',
      up: 'up',
      down: 'down',
      catch: 'catch'
    },
  },

  /**
   * 组件生命周期函数，在组件实例进入页面节点树时执行
   */
  attached: function () {
    //计算视频高度
    var videoAreaHeight = app.globalData.pageHeight - 300
    if (videoAreaHeight > 909) {
      videoAreaHeight = 909;
    }

    this.setData({
      videoAreaHeight: videoAreaHeight,
    })
  },

  /**
   * 组件生命周期函数，在组件实例被从页面节点树移除时执行
   */
  detached: function() {
    this.clearListener();
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 清理全局监听
     */
    clearListener: function() {
      if (this.timeInterVal) {
        clearInterval(this.timeInterVal);
      }
      if (this.showResultInterval) {
        clearInterval(this.showResultInterval);
      }
      this.setData({
        showResult: false,
      })
      if (this.SocketTask) {
        this.SocketTask.close();
      }
    },

    /**
     * 声音开关
     */
    voiceSwitch: function () {
      this.triggerEvent('voiceSwitch', {}, {})
    },

    /**
     * 开始游戏
     */
    gameStart: function () {
      console.log('开始新的游戏');
      this.setData({
        message: '游戏中请勿返回或退出'
      })
      var gameInfo = this.data.gameInfo;
      this.game_record_id = gameInfo.id;
      this.SocketTask = wx.connectSocket({
        url: gameInfo.assign_info.ws_url_d
      })
      this.SocketTask.onOpen((res) => {
        console.log('WebSocket连接打开');
        this.socketOpen = true;
        this.checkResult();
      })
      this.SocketTask.onError((res) => {
        console.log('WebSocket连接打开失败，请检查！');
        this.exceptionHandle();
      })
      this.hasCatched = false;
      //开始计算时间
      this.time = gameInfo.assign_info.time - 2;
      this.setData({
        time: this.time,
      })
      this.timeCountDown();
    },

    /**
     * 游戏倒计时
     */
    timeCountDown: function () {
      this.timeInterVal = setInterval(() => {
        this.time--;
        if (this.time < 0) {
          this.catchGoods();
        } else {
          this.setData({
            time: this.time
          })
        }
      }, 1000);
    },

    /**
     * 按住方向键
     */
    moveAction(e) {
      var dir = e.currentTarget.dataset.dir;
      var dirKey = this.data.dirKey;
      dirKey[dir] = dir + '-cli';
      this.setData({
        dirKey: dirKey
      })
      if (this.socketOpen) {
        var action = "";
        if (dir == 'up') {
          action = "2";
        } else if (dir == 'down') {
          action = "1";
        } else if (dir == 'left') {
          action = "3";
        } else if (dir == 'right') {
          action = "4";
        }
        this.SocketTask.send({
          data: JSON.stringify({ "type": "Control", "data": action }),
        })
      }
    },

    /**
     * 松开方向键
     */
    moveStop(e) {
      var dir = e.currentTarget.dataset.dir;
      var dirKey = this.data.dirKey;
      dirKey[dir] = dir;
      this.setData({
        dirKey: dirKey
      })
      if (this.socketOpen) {
        this.SocketTask.send({
          data: JSON.stringify({ "type": "Control", "data": "55" }),
        })
      }
    },

    /**
     * 抓取商品
     */
    catchGoods: function () {
      if (this.socketOpen && !this.hasCatched) {
        this.setData({
          'dirKey.catch': 'catch-cli'
        })
        setTimeout(() => {
          this.setData({
            'dirKey.catch': 'catch'
          })
        }, 200)
        this.hasCatched = true;
        this.SocketTask.send({
          data: JSON.stringify({ "type": "Control", "data": "5" }),
        })
        clearInterval(this.timeInterVal);
      }
    },

    /**
     * 监听游戏结果
     */
    checkResult: function () {
      this.SocketTask.onMessage((res) => {
        var data = JSON.parse(res.data);
        if (data.type == 'Result') {
          this.setData({
            showResult: true,
            gameResult: data.data.operate_result
          })
          this.SocketTask.close();
          this.socketOpen = false;
          this.game_record_id = null;
          this.showResultTimeCountDown();
        }
      })
    },

    /**
     * 游戏结束5s倒计时
     */
    showResultTimeCountDown: function() {
      this.result_time = 5;
      this.setData({
        result_time: this.result_time,
      })
      this.showResultInterval = setInterval(() => {
        this.result_time--;
        if (this.result_time < 0) {
          this.backToGoodsDetail();
          return;
        }
        this.setData({
          result_time: this.result_time
        })
      }, 1000);
    },

    /**
     * 返回商品详情页面
     */
    backToGoodsDetail: function () {
      this.clearListener();
      this.triggerEvent('gameover', {}, {});
      // wx.navigateBack({
      //   delta: 1
      // })
    },

    /**
     * 再玩一次
     */
    playAgain: function() {
      if (this.showResultInterval) {
        clearInterval(this.showResultInterval)
      }
      this.setData({
        showResult: false,
      })
      this.triggerEvent('playAgain', {}, {});
    },

    /**
     * 领取商品
     */
    takeGoods: function() {
      wx.redirectTo({
        url: '../goods/catched_list/catched_list',
      })
    },

    /**
     * 监听视频状态变化
     */
    RtmpStateChange(e) {
      console.log('live-player code:', e.detail.code)
      if (e.detail.code == 2003) {
        //视频加载成功
        if (this.data.roomStatus == 'searching') {
          this.triggerEvent('loaded', {}, {})
        }
      }
    },
    error(e) {
      console.error('live-player error:', e.detail.errMsg)
    },

    netstatusChange(e) {
      console.log('netstatusChange', e.detail.info);
      if (e.detail.info.netSpeed == 0 && this.data.roomStatus == 'playing') {
        this.exceptionHandle();
      }
    },

    /**
     * 异常退出游戏
     */
    exceptionHandle: function() {
      if (this.exitGame != true) {
        this.exitGame = true;
        this.setData({
          message: '网络连接中断，游戏退出'
        })
        setTimeout(() => {
          this.exitGame = false;
          this.backToGoodsDetail();
        }, 2000);
      }
    },

    /**
     * 故障上报
     */
    reportBug: function() {
      if (this.isReporting == true) {
        return;
      }

      if (this.game_record_id) {
        this.isReporting = true;
        setTimeout(() => {
          this.isReporting = false;
        }, 2000)

        app.Ajax({
          method: 'POST',
          url: '/api/index.php?app=game&act=repair',
          data: {
            game_record_id: this.game_record_id,
          },
          success: (res) => {
            wx.showModal({
              title: '故障上报成功',
              content: '关注【玩购说】服务号\r\n将第一时间为你服务处理',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                }
              }
            })
          }
        })
      }
    },
  }
})
